package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.ex.CustomerException;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.service.StudentService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 学生业务层
 * @author GY
 * @version V1.0
 * @date 2025-01-14 11:39
 */
@Service
@RequiredArgsConstructor
public class StudentServiceImpl implements StudentService {
    private final StudentMapper studentMapper;

    @Override
    public PageResult<Student> pageQuery(Student student) {
        PageHelper.startPage(student.getPage(),student.getPageSize());
        List<Student> students = studentMapper.pageQuery(student);
        Page<Student> page =(Page<Student> ) students;
        return new PageResult<>(page.getTotal(),page.getResult());
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        //1.参数校验
        if (ObjectUtils.isEmpty(ids)){
            throw new RuntimeException("Error : StudentServiceImpl - deleteByIds , 非法参数");
        }
        // 2.删除学员
        studentMapper.deleteByIds(ids);
    }

    @Override
    public void save(Student student) {
        Integer count = studentMapper.countByName(student.getName());
        if (count>0){
            throw new CustomerException("用户名已存在,请更换!");
        }
        count =studentMapper.countByPhone(student.getPhone());
        if (count>0){
            throw new CustomerException("手机号已存在,请更换!");
        }
        student.setUpdateTime(LocalDateTime.now());
        student.setCreateTime(LocalDateTime.now());
        student.setViolationCount(0);
        student.setViolationScore(0);
        studentMapper.save(student);
    }

    @Override
    public Student queryById(Integer id) {
        return studentMapper.queryById(id);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    @Override
    public void deductPointsById(Integer id,  Integer score) {

        studentMapper.deductPointsById(id,score);
    }
}
